﻿using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace SerialPortSendTest
{
    public partial class FserialPortSelect : Form
    {
        public FserialPortSelect()
        {
            InitializeComponent();
        }

        private string serialPortName;

        public string SerialPortName { get => serialPortName;}

        private void FserialPortSelect_Load(object sender, EventArgs e)
        {
            GetSerialPortList();
        }

        #region 从注册表获取系统串口列表
        /// <summary> 
        /// 从注册表获取系统串口列表 
        /// </summary> 
        private void GetSerialPortList()
        {
            //string[] portList = System.IO.Ports.SerialPort.GetPortNames();

            RegistryKey keyCom = Registry.LocalMachine.OpenSubKey("Hardware\\DeviceMap\\SerialComm");
            if (keyCom != null)
            {
                string[] sSubKeys = keyCom.GetValueNames();
                cbbSerialPort.Items.Clear();
                foreach (string sName in sSubKeys)
                {
                    string sValue = (string)keyCom.GetValue(sName);
                    this.cbbSerialPort.Items.Add(sValue);
                }
            }
        }
        #endregion

        private void button1_Click(object sender, EventArgs e)
        {
            if(cbbSerialPort.SelectedIndex==-1)
            {
                MessageBox.Show("请选择正确的串口","错误",MessageBoxButtons.OK,MessageBoxIcon.Error);
                return;
            }

            if (string.IsNullOrEmpty(cbbSerialPort.Text))
            {
                MessageBox.Show("串口错误", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            serialPortName = cbbSerialPort.Text;
            DialogResult = DialogResult.OK;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            DialogResult = DialogResult.Cancel;
        }
    }
}
